#ifndef __M_UTIL_H__
#define __M_UTIL_H__

#include <ctime>
#include <string>
#include <sys/stat.h>
#include <iostream>
#include <sys/types.h>
#include <cerrno>
#include <cstring>
#include <cassert>

/*
实用工具类的实现：
    1.获取系统时间(时间戳)
    2.时间戳格式化
    3.判断文件是否存在
    4.获取文件所在路径
    5.创建目录
*/
namespace MyLog
{
    class Time
    {
    public:
        static time_t GetTimeStamp()
        {
            return time(nullptr);
        }
        static std::string FormatTime(const time_t& time, const std::string& timeFmt)
        {
            struct tm* tmp;
            tmp = localtime(&time);
            char buffer[32];
            if(strftime(buffer, sizeof(buffer), timeFmt.c_str(), tmp) == 0)
            {
                std::cout << "时间格式化失败" << std::endl;
                assert(false);
            }
            return std::string(buffer);
        }
    };
    class File
    {
    public:
        static bool exists(const std::string& pathname)
        {
            struct stat st;
            return stat(pathname.c_str(), &st) == 0;
        }

        static std::string GetFilePath(const std::string& pathname)
        {
            size_t pos = pathname.find_last_of("/\\");
            if(pos == std::string::npos)
                return ".";
            return pathname.substr(0, pos + 1);
        }
 
        static bool CreateDirectory(const std::string& pathname)
        {
            if(exists(pathname))
                return true;
            //处理绝对路径第一个是根目录的情况
            size_t pos = pathname[0] == '/' || pathname[0] == '\\' ? 1 : 0;

            pos = pathname.find_first_of("/\\", pos);
            while(pos != std::string::npos)
            {
                std::string NowPathname = pathname.substr(0, pos);
                if(NowPathname.empty() == false && !_CreateDirectory(NowPathname))
                    return false;
                
                pos = pathname.find_first_of("/\\", pos + 1);
            }
            //处理最后无“/\\”的情况
            if(pathname.empty() == false &&!_CreateDirectory(pathname))
                    return false;
            return true;
        }
        private:
        static bool _CreateDirectory(const std::string& NowPathname)
        {
            if(exists(NowPathname))
                return true;
         
            if(mkdir(NowPathname.c_str(), 0775) == -1)
            {
                printf("错误码: %d, 错误描述: %s", errno, strerror(errno));
                return false;
            }
            return true;
        }

    };
}

#endif